import { http, HttpResponse } from 'msw'

/**
 * 获取产品列表 Mock 接口
 * @description 分页获取产品列表数据，支持搜索和分类筛选
 */
export const getProductListHandler = http.get('/api/product/list', ({ request }) => {
  const url = new URL(request.url)
  const page = parseInt(url.searchParams.get('page') || '1')
  const pageSize = parseInt(url.searchParams.get('pageSize') || '10')
  const keyword = url.searchParams.get('keyword') || ''
  const category = url.searchParams.get('category') || ''
  
  // 模拟产品数据
  const products = Array.from({ length: 100 }, (_, index) => ({
    id: index + 1,
    name: `产品${index + 1}`,
    description: `这是产品${index + 1}的详细描述，包含了产品的主要特性和功能介绍。`,
    price: Math.floor(Math.random() * 10000) + 100,
    originalPrice: Math.floor(Math.random() * 15000) + 1000,
    image: `https://via.placeholder.com/300x300?text=Product${index + 1}`,
    category: ['电子产品', '服装配饰', '家居用品', '运动户外', '美妆护肤'][index % 5],
    brand: `品牌${Math.floor(index / 10) + 1}`,
    stock: Math.floor(Math.random() * 1000) + 10,
    sales: Math.floor(Math.random() * 5000),
    rating: (Math.random() * 2 + 3).toFixed(1), // 3.0-5.0 评分
    status: index % 10 === 0 ? 'disabled' : 'active',
    createTime: new Date(Date.now() - Math.random() * 365 * 24 * 60 * 60 * 1000).toISOString(),
    tags: ['热销', '新品', '推荐'].slice(0, Math.floor(Math.random() * 3) + 1)
  }))
  
  // 筛选逻辑
  let filteredProducts = products
  
  if (keyword) {
    filteredProducts = filteredProducts.filter(product => 
      product.name.includes(keyword) || product.description.includes(keyword)
    )
  }
  
  if (category) {
    filteredProducts = filteredProducts.filter(product => product.category === category)
  }
  
  // 分页处理
  const startIndex = (page - 1) * pageSize
  const endIndex = startIndex + pageSize
  const paginatedProducts = filteredProducts.slice(startIndex, endIndex)
  
  return HttpResponse.json({
    code: 200,
    message: '获取成功',
    data: {
      list: paginatedProducts,
      total: filteredProducts.length,
      page,
      pageSize,
      totalPages: Math.ceil(filteredProducts.length / pageSize)
    }
  })
})

/**
 * 获取产品详情 Mock 接口
 * @description 根据产品 ID 获取产品详细信息
 */
export const getProductDetailHandler = http.get('/api/product/:id', ({ params }) => {
  const productId = parseInt(params.id as string)
  
  if (!productId || productId < 1) {
    return HttpResponse.json({
      code: 400,
      message: '产品ID无效',
      data: null
    }, { status: 400 })
  }
  
  // 模拟产品详情数据
  const product = {
    id: productId,
    name: `产品${productId}`,
    description: `这是产品${productId}的详细描述，包含了产品的主要特性和功能介绍。产品采用优质材料制作，具有良好的性能和耐用性。`,
    price: Math.floor(Math.random() * 10000) + 100,
    originalPrice: Math.floor(Math.random() * 15000) + 1000,
    images: [
      `https://via.placeholder.com/600x600?text=Product${productId}-1`,
      `https://via.placeholder.com/600x600?text=Product${productId}-2`,
      `https://via.placeholder.com/600x600?text=Product${productId}-3`
    ],
    category: ['电子产品', '服装配饰', '家居用品', '运动户外', '美妆护肤'][productId % 5],
    brand: `品牌${Math.floor(productId / 10) + 1}`,
    stock: Math.floor(Math.random() * 1000) + 10,
    sales: Math.floor(Math.random() * 5000),
    rating: (Math.random() * 2 + 3).toFixed(1),
    reviewCount: Math.floor(Math.random() * 1000) + 50,
    status: 'active',
    specifications: {
      '尺寸': '20cm x 15cm x 10cm',
      '重量': '500g',
      '材质': '优质塑料',
      '颜色': '黑色/白色/红色',
      '保修期': '1年'
    },
    features: [
      '高品质材料制作',
      '人性化设计',
      '易于使用',
      '性价比高',
      '售后服务完善'
    ],
    createTime: new Date(Date.now() - Math.random() * 365 * 24 * 60 * 60 * 1000).toISOString(),
    tags: ['热销', '新品', '推荐'].slice(0, Math.floor(Math.random() * 3) + 1)
  }
  
  return HttpResponse.json({
    code: 200,
    message: '获取成功',
    data: product
  })
})

/**
 * 获取产品分类列表 Mock 接口
 * @description 获取所有产品分类信息
 */
export const getProductCategoriesHandler = http.get('/api/product/categories', () => {
  const categories = [
    {
      id: 1,
      name: '电子产品',
      icon: '📱',
      description: '手机、电脑、数码配件等',
      productCount: 25
    },
    {
      id: 2,
      name: '服装配饰',
      icon: '👕',
      description: '男装、女装、鞋帽、包包等',
      productCount: 30
    },
    {
      id: 3,
      name: '家居用品',
      icon: '🏠',
      description: '家具、装饰、厨具、清洁用品等',
      productCount: 20
    },
    {
      id: 4,
      name: '运动户外',
      icon: '⚽',
      description: '运动器材、户外装备、健身用品等',
      productCount: 15
    },
    {
      id: 5,
      name: '美妆护肤',
      icon: '💄',
      description: '化妆品、护肤品、个人护理等',
      productCount: 18
    }
  ]
  
  return HttpResponse.json({
    code: 200,
    message: '获取成功',
    data: categories
  })
})

// 导出所有产品相关的处理器
export const productHandlers = [
  getProductListHandler,
  getProductDetailHandler,
  getProductCategoriesHandler
]